// 初始化一个 WebSocket 对象
const ws = new WebSocket('ws://193.112.187.43:8001')
ws.IsReady=false;
// 建立 web socket 连接成功触发事件
ws.onopen = function () {
  // 使用 send() 方法发送数据
  // ws.send("发送数据")
  this.IsReady=true;
  console.log('open')
}

// 接收服务端数据时触发事件
ws.onmessage = evt => {
  var received_msg = JSON.parse(evt.data)  
  dispatch(received_msg)
}

ws.liseners = {}

ws.addLisener = (op, handler) => {
  ws.liseners[op] = ws.liseners[op] || []
  ws.liseners[op].push(handler);
}

function dispatch (serverData) {
  //const drawData = serverData.drawData
  //const posArr = Scale.serverToLocal(drawData.posArr)  
  if (ws.liseners[serverData.op] && ws.liseners[serverData.op].length > 0) {
    ws.liseners[serverData.op].forEach(handler => {
      handler(serverData)
    })
  }
}

// 断开 web socket 连接成功触发事件
ws.onclose = function () {
  console.log('close')
}

export default ws
